package com.xbank.source.xml.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.BizException;
import com.bizmda.bizsip.common.BizMessageInterface;
import com.bizmda.bizsip.converter.Converter;
import com.bizmda.bizsip.source.api.SourceClientFactory;
import com.xbank.client.app.api.PersonalAppInterface;
import com.xbank.client.app.dto.CustomerAndAccountList;
import com.xbank.infrastructure.db.account.domain.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 史正烨
 */
@Slf4j
@RestController
@RequestMapping("/personal")
public class XmlController {
    // 定义一个接口为PersonalAppInterface的，app层服务名为/app/personal的服务调用句柄
    private PersonalAppInterface personalAppInterface = SourceClientFactory
            .getAppServiceClient(PersonalAppInterface.class,"/app/personal");
    // 定义一个接口为平台标准JSON接口（类型固定为BizMessageInterface），app层服务名为/sink/payment1的服务调用句柄
    private BizMessageInterface payment1SinkInterface = SourceClientFactory
            .getAppServiceClient(BizMessageInterface.class,"/sink/payment1");
    // 获取source层消息格式转换器
    private Converter converter = Converter.getSourceConverter("xml-source");

    public XmlController() throws BizException {
    }

    @PostMapping(value = "/getCustomerAndAccountList", consumes = "application/xml", produces = "application/xml")
    public String getCustomerAndAccountList(@RequestBody String inMessage) throws BizException {
        // 消息解包操作
        JSONObject jsonObject = this.converter.unpack(inMessage.getBytes());
        String customerId = (String)jsonObject.get("customerId");
        // 调用app层服务
        CustomerAndAccountList customerAndAccountList = this.personalAppInterface.getCustomerAndAccountList(customerId);
        jsonObject = JSONUtil.parseObj(customerAndAccountList);
        // 消息打包并返回
        return new String(this.converter.pack(jsonObject));
    }

    @PostMapping(value = "/getAccountListByCustomerId", consumes = "application/xml", produces = "application/xml")
    public String getAccountListByCustomerId(@RequestBody String inMessage) throws BizException {
        JSONObject jsonObject = this.converter.unpack(inMessage.getBytes());
        String customerId = (String)jsonObject.get("customerId");
        List<Account> accountList = this.personalAppInterface.getAccountListByCustomerId(customerId);
        jsonObject = new JSONObject();
        jsonObject.set("result",JSONUtil.parseArray(accountList));
        return new String(this.converter.pack(jsonObject));
    }
}